package com.example.micro.netty.server.thread;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * Thread.stop测试
 *
 * @author Code Farmer
 * @create 2020/10/7 3:40 下午
 */
public class StopThreadUnsafe {

    public static User user = new User();

    @Getter
    @Setter
    @ToString
    public static class User {
        private int id;
        private String name;

        public User() {
            id = 0;
            name = "0";
        }
    }

    public static class ChangeObjectThread extends Thread {
        @Override
        public void run() {
            while (true) {
                synchronized (user) {
                    int v = (int) (System.currentTimeMillis() / 1000);
                    user.setId(v);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                    }
                    user.setName(String.valueOf(v));
                }
                Thread.yield();
            }
        }
    }

    public static class ReadObjectThread extends Thread {
        @Override
        public void run() {
            while (true) {
                synchronized (user) {
                    if (user.getId() != Integer.parseInt(user.getName())) {
                        System.out.println(user.toString());
                    }
                }
                Thread.yield();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new ReadObjectThread().start();
        while (true) {
            Thread t = new ChangeObjectThread();
            t.start();
            Thread.sleep(150);
//            t.stop();
        }
    }


}
